package com.example.demo.interceptorToken;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import java.io.IOException;

/**
 * @author hulei
 * @date 2024/1/11 19:48
 * 自定义请求过滤器
 */
//排序优先级,最先执行的过滤器
@Order(0)
public class RequestFilter extends OncePerRequestFilter {

    //spring6.0版本后删除了CommonsMultipartResolver,使用StandardServletMultipartResolver
    //如果是spring6.0版本,此行代码不报错请使用如下
    // private CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    private final StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
    /**
     *
     */
    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        //请求参数有form_data的话，防止request.getHeaders()报已使用,单独处理
        //可能没有传任何参数,所以需要判断request.getContentType()!= null
        if (request.getContentType()!= null && request.getContentType().contains("multipart/form-data")) {
            MultipartHttpServletRequest multiReq = multipartResolver.resolveMultipart(request);
            filterChain.doFilter(multiReq, response);
        }else{
            ServletRequest requestWrapper;
            requestWrapper = new RequestWrapper(request);
            filterChain.doFilter(requestWrapper, response);
        }
    }

}